/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bea.action;

import bea.logic.BananaEngine;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.swing.JEditorPane;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.cookies.EditorCookie;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;
import org.openide.util.Lookup;

@ActionID(category = "Edit",
id = "bea.action.Decrypt")
@ActionRegistration(iconBase = "bea/action/dekrip.png",
displayName = "#CTL_Decrypt")
@ActionReferences({
    @ActionReference(path = "Menu/Edit", position = 3400),
    @ActionReference(path = "Toolbars/Build", position = 600),
    @ActionReference(path = "Shortcuts", name = "DO-D")
})
@Messages("CTL_Decrypt=Dekripsi")
public final class Decrypt implements ActionListener {
    public BananaEngine be = new BananaEngine();
    
    @Override
    public void actionPerformed(ActionEvent e) {
        String msg = "null";
        be = new BananaEngine();
        Node[] arr = TopComponent.getRegistry().getCurrentNodes();
        for (int i = 0; i < arr.length; i++) {
            EditorCookie ec = arr[i].getCookie(EditorCookie.class);
            if (ec != null) {
                JEditorPane[] panes = ec.getOpenedPanes();
                if (panes != null) {
                    msg = panes[0].getText();
                    NotifyDescriptor.InputLine question;
                    question = new NotifyDescriptor.InputLine("Password :",
                        "Decrypt...",
                        NotifyDescriptor.OK_CANCEL_OPTION,
                        NotifyDescriptor.QUESTION_MESSAGE);

                    if (DialogDisplayer.getDefault().notify(question) == NotifyDescriptor.OK_OPTION) {
                        try {
                            be.key.inputKey(question.getInputText().getBytes());
                            be.setcipher(msg.getBytes());
                            //System.out.println(msg.getBytes());
                            be.cfbDecrypt();
                            panes[0].setText(new String(be.gethasil(false),"ISO-8859-1"));

                            NotifyDescriptor d = new NotifyDescriptor.Message("Text Successfully Decrypted", 
                                    NotifyDescriptor.INFORMATION_MESSAGE);
                            DialogDisplayer.getDefault().notify(d);
                        } catch (UnsupportedEncodingException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            }
        }
    }
}
